/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.web.springmvc;

import java.io.IOException;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

/**
 * 类作用：
 * 
 * @author JohnnyZhou@cn.ibm.com 使用说明：
 */
public class ExposedResourceBundleMessageSource extends ReloadableResourceBundleMessageSource {
	Logger log = LoggerFactory.getLogger(getClass());

	private static final String PROPERTIES_SUFFIX = ".properties";
	private ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

	@Override
	protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) {
		Properties properties = new Properties();
		log.debug("refreshProperties : {}...", filename);
		long lastModified = -1;
		try {
			Resource[] resources = resolver.getResources(filename + PROPERTIES_SUFFIX);

			for (Resource resource : resources) {

				// log.debug("Handling resource: {}...", resource);
				String sourcePath = resource.getURI().toString().replace(PROPERTIES_SUFFIX, "");
				Properties props = super.refreshProperties(sourcePath, propHolder).getProperties();
//				Properties props = loadProperties(resource, filename);
				properties.putAll(props);
				if (lastModified < resource.lastModified())
					lastModified = resource.lastModified();
			}
		} catch (IOException e) {
			log.error("Error to get resource.", e);
		}
		return new PropertiesHolder(properties, lastModified);
	}

	public Set<Object> getKeys(Locale locale) {
		PropertiesHolder propsHolder = getMergedProperties(locale);
		return propsHolder.getProperties().keySet();
	}

}
